<template>
  <el-card class="m-8">
    <section slot="header" class="flex items-center justify-center mb-10">
      <p class="ml-10">奖池选择：</p>
      <el-select v-model="poolId" placeholder="请选择">
        <el-option
          v-for="item in poolOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button class="mr-4" type="primary" @click="changePool">确认切换</el-button>
    </section>


    <section slot="header" class="mb-4 flex items-center justify-between">
      <div>
        <el-button class="mr-4" type="primary" @click="handleAdd">新增</el-button>
        <el-button type="warning" @click="handleEditAll">批量编辑</el-button>
        <el-button v-if="listQuery.is_next === 0" type="danger" @click="handleReplace">替换新奖池</el-button>
      </div>
    </section>

    <el-table :data="tableList" align="center" border class="mt-4" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="奖励名称" prop="detail.name"/>
      <el-table-column label="奖励类型" prop="reward_type">
        <template slot-scope="scoped">
          {{ scoped.row.reward_type === 'gift' ? '礼物': '装扮' }}
        </template>
      </el-table-column>
      <el-table-column label="奖励价值（m豆）" prop="detail.price">
        <template slot-scope="{row}">
          {{ row.reward_type === 'gift' ? row.detail.price: '--' }}
        </template>
      </el-table-column>
      <el-table-column label="有效期（天）" prop="count">
        <template slot-scope="{row}">
          {{ row.reward_type === 'gift' ? '--': row.count }}
        </template>
      </el-table-column>
      <el-table-column label="礼物图案" prop="picture">
        <template slot-scope="scoped">
          <el-image :lazy="true" :src="scoped.row.detail.picture" class="imageStyle" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="权重" prop="weight"/>
      <el-table-column label="添加时间" prop="created_at"/>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="{row}">
          <el-button type="primary" @click="handleEdit(row)">编辑</el-button>

          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <cus-pagination
      :limit.sync="listQuery.perPage"
      :page.sync="listQuery.page"
      :total="total"
      @pagination="initData"
    />

    <el-dialog
      :title="isEdit?'编辑':'新增'"
      :visible.sync="addDialog2"
      lock-scroll
      width="30%"
      @close="closeAddDialog2"
    >
      <el-form ref="form" :inline="false" :model="form" :rules="rules" label-width="150px" size="normal">
        <el-form-item v-if="!isEdit" label="奖励类型" prop="reward_type">
          <el-select v-model="form.reward_type" clearable filterable placeholder="请选择受限类型">
            <el-option
              v-for="item in rewardType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.reward_type === 'gift'" :label="isEdit?'选择替换礼物':'选择礼物'" prop="reward_id">
          <el-select v-model="form.reward_id" remote clearable filterable :remote-method="remoteMethod" placeholder="请选择礼物" @clear="clear">
            <el-option
              v-for="item in menuList1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-else :label="isEdit?'选择替换奖励':'选择奖励'" prop="reward_id">
          <el-select v-model="form.reward_id" remote clearable filterable :remote-method="remoteMethod2" placeholder="请选择奖励" @clear="clear2">
            <el-option
              v-for="item in menuList2"
              :key="item.id"
              :label="item.product_name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.product_name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="权重" prop="weight">
          <el-input type="number" v-model="form.weight"></el-input>
        </el-form-item>

        <el-form-item type="number" v-if="form.reward_type=== 'product'" label="奖励有效期" prop="count">
          <el-input v-model="form.count">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>

      </el-form>

      <section slot="footer">
        <el-button @click="addDialog2 = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </section>
    </el-dialog>

    <el-dialog
      :visible.sync="editAllDialogVisible"
      title="批量编辑"
      width="435px"
      @close="editAllCount = undefined"
    >
      <p class="mb-4">提示：您已选择 {{ this.titleList.toString() }} 等......多条数据</p>
      <span style="color: red;">*</span>
      <span>修改奖励权重：</span>
      <el-input type="number" v-model="editAllCount"></el-input>

      <span slot="footer" class="dialog-footer">
            <el-button @click="editAllDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEditAll">确 定</el-button>
        </span>
    </el-dialog>
  </el-card>


</template>

<script>
import { boxList, boxAdd, boxEdit, boxBatch, boxDel, productList, boxReplace } from '@/api/sunGame/sunGame'

// 礼物下拉数据
import { getData } from '@/api/roomGift/giftList'

export default {
  data() {
    return {
      poolId: 0,
      poolOptions: [
        {
          value: 0,
          label: '本期奖池'
        },
        {
          value: 1,
          label: '下期奖池'
        }
      ],
      rewardType: [
        {
          value: 'gift',
          label: '礼物'
        },
        {
          value: 'product',
          label: '装扮'
        },
        // {
        //   value: 3,
        //   label: '碎片'
        // }
      ],
      selectData: '',
      menuList1: [],
      menuList2: [],
      tableList: [],
      user_code: '',
      nickname: '',
      dateList: undefined,
      listQuery: {
        user_code: '',
        nickname: '',
        page: 1,
        perPage: 10,
        is_next: 0
      },
      meta: {
        page: 1,
        perPage: 20

      },
      total: 0,
      /* 弹出框开关 */
      addDialog: false,
      addDialog2: false,

      rejectLoading: false,
      passLoading: false,
      id: '',
      // 拒绝原因
      reject_reason: '',
      form: {
        weight: undefined,
        id: undefined,
        reward_id: undefined,
        count: undefined,
        reward_type: 'gift',
        is_next: 1
      },
      rules: {
        weight: [{ required: true, message: '请输入奖励权重', trigger: 'blur' }],
        reward_type: [{ required: true, message: '请选择', trigger: 'change' }],
        reward_id: [{ required: true, message: '请选择', trigger: 'change' }],
        count: [{ required: true, message: '请输入奖励有效期', trigger: 'change' }]
      },
      multipleSelection: [],
      dataIds: '',
      editAllCount: '',
      editAllDialogVisible: false,
      isEdit: false,
      optionQuery: {
        page: 1,
        page_size: 50,
        cate_id: 0,
        style_id: 0
      },
      titleList: []
    }
  },
  created() {
    this.initData()
    this.handleGetData()
    this.handleGetProductList()
  },
  methods: {
    handleGetData() {
      getData(this.optionQuery).then(res => {
        res.data.data.map(item => {
          
          item.name = item.name + `(${item.price}M豆)`
          
        })
        this.menuList1 = res.data.data
      })
    },
    handleGetProductList() {
      productList(this.optionQuery).then(res => {
        // res.data.data.map(item => {
          
        //   item.product_name = item.product_name + `(${item.product_price.length?item.product_price[0].day:''}天)`
          
        // })
        this.menuList2 = res.data.data
      })
    },
    changePool() {
      console.log(this.poolId)
      this.listQuery.is_next = this.poolId
      this.form.is_next = this.poolId
      this.initData()
    },
    confirmEditAll() {
      if (!this.editAllCount) {
        this.$message({
          message: '输入正确的值',
          type: 'warning'
        })
      } else {
        boxBatch({
          ids: this.dataIds,
          weight: this.editAllCount,
          is_next: this.listQuery.is_next
        }).then(res => {
          if (res.code === 200) {
            this.initData()
            this.editAllDialogVisible = false
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
        })
      }
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击批量删除
    handleEditAll() {
      if (this.multipleSelection.length < 2) {
        this.$message({
          message: '请选择2条或2条以上的内容',
          type: 'warning'
        })
        return
      } else {
        let ids = ''
        this.titleList = []
        for (let key in this.multipleSelection) {
          if(key < 3) {
            this.titleList.push(this.multipleSelection[key].detail.name)
          }
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = ids
      }
      this.editAllDialogVisible = true
    },
    handleEdit(row) {
      this.isEdit = true
      if(row.reward_type === 'gift') {
        this.optionQuery.id = row.reward_id
        this.handleGetData(this.optionQuery)
      }
      if(row.reward_type === 'product') {
        this.optionQuery.id = row.reward_id
        this.handleGetProductList(this.optionQuery)
      }
      this.form = JSON.parse(JSON.stringify(row))
      this.form.is_next = this.poolId
      this.listQuery.is_next = this.poolId
      this.addDialog2 = true
    },
    handleAdd() {
      this.isEdit = false
      this.form.is_next = this.poolId
      this.listQuery.is_next = this.poolId
      this.addDialog2 = true
      this.optionQuery.gift_name = undefined
      this.optionQuery.name = undefined
      this.optionQuery.id = undefined
      this.handleGetData()
      this.handleGetProductList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.initData()
    },
    async initData() {
      try {
        for (let key in this.listQuery) {
          this.listQuery[key] = !this.listQuery[key] ? undefined : this.listQuery[key]
        }
        if(!this.listQuery.is_next) {
          this.listQuery.is_next = 0
        }
        const { data } = await boxList(this.listQuery)
        this.listQuery.page = data.meta.page
        this.total = data.meta.total
        this.tableList = data.list
      } catch (e) {
        console.error(e)
      }
    },
    handleDelete(row) {
      this.$confirm('此操作不可恢复，是否继续删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { code, data } = await boxDel({
          id: row.id,
          is_next: this.listQuery.is_next
        })
        if (code === 200) {

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.initData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onSubmit() {

      this.$refs['form'].validate(valid => {
        if (valid) {
          for (let key in this.form) {
            this.form[key] = !this.form[key] ? undefined : this.form[key]
          }
          if(!this.form.is_next) {
            this.form.is_next = 0
          }
          if(this.form.id) {
            boxEdit(this.form).then(res => {
              if (res.code === 200) {
                this.initData()
                this.addDialog2 = false
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
            })
          }else {
            boxAdd(this.form).then(res => {
              if (res.code === 200) {
                this.initData()
                this.addDialog2 = false
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
            })
          }
        }
      })




      
    },
    closeAddDialog() {
      this.user_code = undefined
    },
    closeAddDialog2() {
      if (this.$refs['form']) {
        this.$refs['form'].clearValidate() // 清除整个表单的校验
        this.$refs['form'].resetFields() // 清除整个表单的校验
      }
      this.form = {
        price: undefined,
        id: undefined,
        name: undefined,
        sort: undefined,
        reward_type: 'gift'
      }
    },
    remoteMethod(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.gift_name = query
        this.handleGetData(this.optionQuery)
      }
    },
    remoteMethod2(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.name = query
        this.handleGetProductList(this.optionQuery)
      }
    },
    clear() {
      this.form.reward_id = undefined
      this.optionQuery = {
        page: 1,
        page_size: 100,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetData(this.optionQuery)
    },
    clear2() {
      this.form.reward_id = undefined
      this.optionQuery = {
        page: 1,
        page_size: 100,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetProductList(this.optionQuery)
    },
    handleReplace() {
      this.$confirm('确认替换奖池?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        boxReplace().then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.initData()
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      
    },
  }
}
</script>

<style scoped>
.imageStyle {
  width: 150px;
}

.input {
  width: 200px;
}
</style>
